<template>
  <div class="home">
    <el-container>
      <el-header>
        <div class="bookmarks-header-bar">
          Header
          <search-bar @search="searchHandle($event)" @clear="clearHandle()"></search-bar>
        </div>
      </el-header>
      <el-container>
        <el-aside >
          <bookmarks-tree :tree-items="treeItems" @selectBookmark="bookmarksSelectedHandle" @openPage="openPageHandle($event)"></bookmarks-tree>
        </el-aside>
        <el-container>
          <el-main>
            <div v-if="pageType === getPageTypeEnum().NavPage && treeItems.length > 0">
              <bookmark-list :nav-items="navItems" :items-list="itemsList" :items-group="itemsGroup" @openPage="openPageHandle($event)"></bookmark-list>
            </div>
            <div v-else-if="pageType === getPageTypeEnum().SearchPage">
              <search-list :search-res-items="searchResItems" @goBack="switchPage(getPageTypeEnum().NavPage)" @openPage="openPageHandle($event)"></search-list>
            </div>
          </el-main>
          <el-footer>Footer</el-footer>
        </el-container>
      </el-container>
    </el-container>
  </div>
</template>
<script>
/**
 * 书签操作
 * 1. 增删改查
 * 》2. 搜索，关键字高亮
 * 3. 数据导出（XML，JSON）；导入（XML，JSON）
 * 4. 兼容360浏览器
 * 5. 增加图标库（图标库，本地图标）
 * 》6. 快速导航栏（头部显示收藏夹导航路径，左边树状显示，右边折叠面板，树状与折叠面板关联）
 * 7. 换肤功能
 */
import BookmarksTree from '@/components/Bookmarks/BookmarksTree.vue'
import BookmarkList from '@/views/BookmarkList'
import SearchList from '@/views/SearchItemList'
import SearchBar from '@/components/Search/SearchBar.vue'
import { ITEMS_GROUP, BOOK_MARKS, SEARCH_RES_LIST } from './dataS'
import {objectArrayGroupBySort} from './utils/objectArrayExt'
import {PAGE_TYPE} from './utils/enumObject'

function iteratorSearchBMTree(searchResultMap, navRouter, srcArr, findText) {
  if (!findText || findText.trim().length === 0) return;
  let resArr = [];
  for(let i=0; i < srcArr.length; i++) {
    if (Array.isArray(srcArr[i].children)) {
      let routerKey = `${navRouter} -> ${srcArr[i].title}`;
      let childArr = iteratorSearchBMTree(searchResultMap, routerKey, srcArr[i].children, findText);
      childArr.length && (searchResultMap[routerKey] = childArr);
    } else {

      if (!srcArr[i].title.toLowerCase().includes(findText.toLowerCase())) continue;
      resArr.push({
        id: srcArr[i].id,
        name: srcArr[i].title,
        url: srcArr[i].url,
        searchContent: findText
      });
    }
  }
  return resArr;
}

export default {
  components: {
    BookmarksTree,
    BookmarkList,
    SearchList,
    SearchBar
    // SearchResultTab
  },
  data () {
    return {
      itemsList: [],
      itemsGroup: [],
      pageType: '',
      treeItems: [], // BOOK_MARKS[0].children,
      navItems: [{title:'收藏夹', id: 0}],
      searchResItems: []//SEARCH_RES_LIST
    }
  },
  mounted() {
    this.switchPage(PAGE_TYPE.NavPage); // PAGE_TYPE.SearchPage
    // this.treeItems = BOOK_MARKS[0].children;
    let thisSelf = this;
    chrome.bookmarks.getTree(function(nodes) {
      thisSelf.treeItems = nodes[0].children;
    })
  },
  methods: {
    getPageTypeEnum(){
      return PAGE_TYPE;
    },
    bookmarksSelectedHandle(bookmarksItems, navRouters) {
      this.updatedNavRouters(navRouters);

      if (Object.prototype.toString.call(bookmarksItems) !== '[object Array]' && bookmarksItems.length === 0) return;
      const groupArr = this.handledBookmarkItems(bookmarksItems);
      this.itemsList = groupArr.files;
      this.itemsGroup = groupArr.dirs;
    },
    updatedNavRouters(navRouters) {
      Array.isArray(navRouters) && (navRouters.unshift(this.navItems[0])) && (this.navItems = navRouters);
    },
    handledBookmarkItems(bookmarksItems){
      const groupArr = bookmarksItems.reduce((accu, currVal) => {
          currVal.url ? accu.files.push(currVal) : accu.dirs.push(currVal);
          return accu
        },{ files: [], dirs: [] })

      // 收藏夹目录级内容排序，使目录级排到最后显示
      groupArr.dirs.map(item=> {
        return item.children.sort(objectArrayGroupBySort('array', 'children', '', 'ASC'));
      });
      return groupArr;
    },
    switchPage(currPage){
      this.pageType = currPage;
    },
    searchHandle(searchText) {
      this.switchPage(PAGE_TYPE.SearchPage);

      let searchResultMap = {}
      let routerRootKey = '收藏夹'
      let rootArr = iteratorSearchBMTree(searchResultMap, routerRootKey, this.treeItems, searchText);
      rootArr.length && (searchResultMap[routerRootKey] = rootArr);

      let searchResArr = []
      let resCount = 1;
      for(let resItem in searchResultMap) {
        searchResArr.push({
          id: resCount++,
          navRouter: resItem,
          searchList: searchResultMap[resItem]
        })
      }
      this.searchResItems = searchResArr;

      // console.log('************ search Result : ', searchResultMap, JSON.stringify(searchResultMap));
    },
    clearHandle() {
      console.log('******* clearHandle ');
      this.switchPage(PAGE_TYPE.NavPage);
    },
    openPageHandle(bmItem){
      console.log('*********** openPageHandle : ', bmItem);
      if (bmItem && bmItem.url) {
        const winName = bmItem.title;
        const winConfig = `
          menubar=yes,
          location=yes,
          resizable=yes,
          scrollbars=yes,
          status=yes,
          width=400,
          height=400,
          `
        const winRef = window.open(bmItem.url, winName, winConfig);
      }
    }
  }
}
</script>
<style>
body{
  margin: 0px;
  font-size: 14px;
}
</style>
<style scoped>
.home{
  height: 100vh;
  width:810px;
  background-color: #eee;
}
.el-container {
  height: 100%;
}
.el-header,
.el-footer {
  background-color: #eee;
  color: var(--el-text-color-primary);
  text-align: center;
  line-height: 60px;
}

.el-aside {
  width:260px !important;
  background-color: #d3dce6;
  color: var(--el-text-color-primary);
  text-align: center;
  border-right: 1px solid #ddd;
}

.el-main {
  --el-main-padding: 0px;
  background-color: white;
  /* color: var(--el-text-color-primary); */
  text-align: center;
}

.bookmarks-header-bar{
  display: flex;
  justify-content: space-between;
}
</style>